<?php

namespace app\api\logic;

use think\facade\Db;
use app\data\util\HttpUtil;
use think\exception\ValidateException;
use think\facade\Cache;
use app\api\logic\ApiOrderLogic;

class ApiProductLogic extends BasicLogic
{
    public function __construct()
    {

    }

    public function PollingStores()
    {
        $where2[] = ['type', '=', "shopify"];
        $shop_id = 0;
        $shops = Cache::store('redis')->get('shops_shopify');
        if (empty($shops)) {  
            $shopRecords = Db::name('shops')
                ->where($where2)
                ->where('status',1)
                ->field("id")->select()->toarray();
            if(!empty($shopRecords)){
                $shops = array_column($shopRecords, 'id');
                Cache::store('redis')->set('shops_shopify', $shops, 3600 * 24); // 缓存24小时  
            }
        } 
        if (!empty($shops)) {  
            $shop_id = array_shift($shops); 
            if (!empty($shops)) {  
                Cache::store('redis')->set('shops_shopify', $shops, 3600 * 24);
            }else{
                Cache::store('redis')->delete('shops_shopify');
            }
        }
        return $shop_id;
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 订单列表
     * @author zhangheng
     */
    public function ApiProductList($params = [])
    {
        $shop_id        = $params['shop_id'] ?? 0;
        
        if(empty($shop_id)){
            //轮询店铺
            $shop_id = $this->PollingStores();
            if (empty($shop_id)) {
                return json(DefaultResponse(201, false, '暂无店铺!', null));
            }
        }
        
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
        $version        = Config('Logisticskey.shopify.api_versoin');
        $operation      = Config('Logisticskey.shopify.operation');
        $url            = $shop_info['myshopify_domain'].$version . $operation;
        
        $limit = 250;
        //拉取历史数据,在拉取之前先把ControlUpdateTime时间设置成0
        if (!empty($shop_info['ControlUpdateTime'])) {
            $created_at_max = $shop_info['ControlUpdateTime'];
        } else {
            date_default_timezone_set('Asia/Shanghai');
            $created_at_max1 = date('Y-m-d', time());
            $created_at_max2 = date('H:i:s', time());
            $created_at_max = $created_at_max1 . 'T' . $created_at_max2 . '-04:00';
        }
        $url = $url . '?updated_at_max=' . $created_at_max . '&limit=' . $limit;

        $return = HttpUtil::getUrl($url, $shop_info);
// halt($return);
        if (!empty($return['errors'])) {
            return json(DefaultResponse(201, false, json_encode($return['errors']), null));
        }
        if(!empty($return)){
            // Db::startTrans();
            // try {
                //存入数据
                $this->ProcessProduct($return,$shop_info['id']);
                
            //     Db::commit();
                return json(DefaultResponse(200, true, '操作成功', ''));
            // } catch (ValidateException $e) {
            //     Db::rollback();
            //     return json(DefaultResponse(200, true, $e->getError(), ''));
            // } catch (\Exception $e) {
            //     Db::rollback();
            //     return json(DefaultResponse(200, true, $e->getMessage(), ''));
            // }
        }else{
            return json(DefaultResponse(200, true, '暂无数据', ''));
        }
    }
    
    public function ApiProductInfo($params = [])
    {
        $shop_id        = $params['shop_id'] ?? 0;
        $product_id        = $params['product_id'] ?? 0;
        
        if(empty($product_id)){
            return json(DefaultResponse(201, false, '暂无产品!', null));
        }
        if(empty($shop_id)){
            return json(DefaultResponse(201, false, '暂无店铺!', null));
        }
        
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
        $version        = Config('Logisticskey.shopify.api_versoin');
        $operation      = Config('Logisticskey.shopify.operation');
        $url            = $shop_info['myshopify_domain'].$version . $operation."?ids=".$product_id;

        $return = HttpUtil::getUrl($url, $shop_info);

        if (!empty($return['errors'])) {
            return json(DefaultResponse(201, false, json_encode($return['errors']), null));
        }
        halt($return);
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 产品刊登
     * @author zhangheng
     */
    public function ApiProductAdd($params = [])
    {
        $shop_id        = $params['shop_id'] ?? 0;
        $data        = $params ?? [];
        if(empty($shop_id)){
            return json(DefaultResponse(201, false, '暂无店铺!', null));
        }
        if(empty($data)){
            return json(DefaultResponse(201, false, '暂无数据!', null));
        }
        
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
        $version        = Config('Logisticskey.shopify.api_versoin');
        $operation      = Config('Logisticskey.shopify.operation');
        $url            = $shop_info['myshopify_domain'].$version . $operation;
        
        //添加产品需要的参数
        $data = $this->params_data($data);

        $return = HttpUtil::postUrl($url,$data,$shop_info);

        if (!empty($return['errors'])) {
            return json(DefaultResponse(201, false, json_encode($return['errors']), null));
        }
        if (isset($return['product']['id']) && !empty($return['product']['id'])) {
            $product_id = $return['product']['id'];
            return json(DefaultResponse(200, true, '产品刊登成功',$product_id));
        }
        return json(DefaultResponse(201, true, '产品刊登失败'));
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 产品修改
     * @author zhangheng
     */
    public function ApiProductEdit($params = [])
    {
        $shop_id        = $params['shop_id'] ?? 0;
        $data        = $params ?? [];
        $product_id        = $params['product_id'] ?? [];
        if(empty($shop_id)){
            return json(DefaultResponse(201, false, '暂无店铺!', null));
        }
        if(empty($data)){
            return json(DefaultResponse(201, false, '暂无数据!', null));
        }
        if(empty($product_id)){
            return json(DefaultResponse(201, false, '请添加产品id!', null));
        }
        
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
        $version        = Config('Logisticskey.shopify.api_versoin');
        $url            = $shop_info['myshopify_domain'].$version . "/products/" . $product_id . ".json";
        
        //添加产品需要的参数
        $data = $this->params_data($data);

        $return = HttpUtil::putUrl($url,$data,$shop_info);

        if (!empty($return['errors'])) {
            return json(DefaultResponse(201, false, json_encode($return['errors']), null));
        }
        if (isset($return['product']['id']) && !empty($return['product']['id'])) {
            $product_id = $return['product']['id'];
            return json(DefaultResponse(200, true, '产品修改成功',$product_id));
        }
        return json(DefaultResponse(201, true, '产品修改失败'));
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 产品删除
     * @author zhangheng
     */
    public function ApiProductDelete($params = [])
    {
        $shop_id        = $params['shop_id'] ?? 0;
        $product_id        = $params['product_id'] ?? [];
        if(empty($shop_id)){
            return json(DefaultResponse(201, false, '暂无店铺!', null));
        }
        if(empty($product_id)){
            return json(DefaultResponse(201, false, '请添加产品id!', null));
        }
        
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
        $version        = Config('Logisticskey.shopify.api_versoin');
        $url            = $shop_info['myshopify_domain'].$version . "/products/" . $product_id . ".json";

        $return = HttpUtil::delUrl($url,$shop_info);

        if (!empty($return['errors'])) {
            return json(DefaultResponse(201, false, json_encode($return['errors']), null));
        }
        if (isset($return['product']['id']) && !empty($return['product']['id'])) {
            $product_id = $return['product']['id'];
            return json(DefaultResponse(200, true, '产品删除成功',$product_id));
        }
        return json(DefaultResponse(201, true, '产品删除失败'));
    }

    /**
    * @desc    添加产品需要的参数
    * @date    2024/11/25
    * @author  zhangheng
    */
    public function params_data($product)
    {
        $arr = array();
        $arr['title'] = $product['title'];
        $arr['body_html'] = $product['body_html'];
        $arr['vendor'] = $product['vendor'];
        $arr['product_type'] = $product['product_type'];
        $arr['tags'] = $product['tags'];
        $arr['status'] = $product['status'];
        $arr['variants'] = array();
        $arr['options'] = array();
        $arr['images'] = array();
        if (!empty($product['variants'])) {
            foreach ($product['variants'] as $kvariants => $vvariants) {
                $avariants = array();
                $avariants['sku'] = $vvariants['sku'];
                $avariants['option1'] = $vvariants['option1'];
                $avariants['option2'] = $vvariants['option2'];
                $avariants['option3'] = $vvariants['option3'];
                $arr['variants'][] = $avariants;
            }
        }
        if (!empty($product['options'])) {
            foreach ($product['options'] as $koptions => $voptions) {
                $aoptions = array();
                $aoptions['name'] = $voptions['name'];
                if (!empty($voptions['values'])) {
                    $aoptions['values'] = implode(',', $voptions['values']);
                }
                $arr['options'][] = $aoptions;
            }
        }
        if (!empty($product['images'])) {
            foreach ($product['images'] as $kimages => $vimages) {
                $aimages = array();
                $aimages['src'] = $vimages['src'];
                $arr['images'][] = $aimages;
            }
        }
        $newdata['product'] = $arr;
    }
    
    
    /**
    * 方法详情
    * @param array params
    */
    public function ProcessProduct($return,$shop_id)
    {
        //存入时间
        $ApiOrderLogic = new ApiOrderLogic();
        $products = $return['products'];
        if (is_array($products) && !empty($products)) {
            date_default_timezone_set('Asia/Shanghai');
            foreach ($products as  $product) {
                // $row = Db::name('product_api')->where('product_id',$product['id'])->find();
                
                // if(!empty($row)){
                //     //2.同步修改
                    // if($type !== '2'){
                        // $this->SynchronizzeModifications($product,$shop_id);
                    // }
                // }else{
                    //1.新增时创建
                    $this->SynchronizeModifications($product,$shop_id);
                // }

                $ControlUpdateTime = 0;
                //移除时间字符串中的'T'和时区部分
                if(!empty($ControlUpdateTime)){
                    $createtime = $ApiOrderLogic->dateTimeStr($product['updated_at']);
                    $ControlUpdateTimeTimeStamp = $ApiOrderLogic->dateTimeStr($ControlUpdateTime);
                    if($ControlUpdateTimeTimeStamp > $createtime){
                        $ControlUpdateTime = $product['updated_at'];
                    }
                }else{
                    $ControlUpdateTime = $product['updated_at'];
                }
                $update_shop['ControlUpdateTime'] = $ControlUpdateTime;
            }

        }
        
        if (!empty($update_shop)){
            //打印出2024-07-18T00:12:11-00:00
            $ControlUpdateTime = $ApiOrderLogic->dateTimeStr($update_shop['ControlUpdateTime']);
            $update_shop['ControlUpdateTime'] = date('Y-m-d',$ControlUpdateTime+3600*24).'T00:00:00-00:00';
            // halt($update_shop);
            Db::name('shops')
                ->where('id', $shop_id)
                ->update($update_shop);
        }


        return true;
    }

    
    
    /**
    * 新增产品
    * @param array params
    */
    public function SynchronizeModifications($product,$shop_id)
    {
        //订单主表
        $insert = [
            'product_id' => $product['id'] ?? "",
            'shop_id' => $shop_id ?? "",
            'title' => $this->removeNonAscii($product['title']) ?? "",
            'body_html' => "",
            // 'body_html' => $ApiOrderLogic->removeNonAscii($product['body_html']) ?? "",
            'vendor' => $this->removeNonAscii($product['vendor']) ?? "",
            'product_type' => $this->removeNonAscii($product['product_type']) ?? "",
            'tags' => $this->removeNonAscii($product['tags']) ?? "",
            'handle' => $this->removeNonAscii($product['handle']) ?? "",
            'status' => $product['status'] ?? "",
            'created_at' => $product['created_at'] ?? "",
            'updated_at' => $product['updated_at'] ?? "",
            'published_at' => $product['published_at'] ?? "",
        ];
        $sku = '';
        //variants
        if($product['variants'] && is_array($product['variants'])){
            $sku = $this->addvariants($product['id'],$product['variants']);
        }
        //images
        if($product['images'] && is_array($product['images'])){
            $this->addimages($product['id'],$product['images']);
        }
        $insert['sku'] = $sku;
        $orderdb = Db::name('product_api')->where('product_id',$product['id'])->find();
        if(!empty($orderdb)){
            Db::name('product_api')->where('product_id',$product['id'])->update($insert);
        }else{
            Db::name('product_api')->insert($insert);
        }

        return true;
    }

    /**
    * 修改产品
    * @param array params
    */
    public function SynchronizzeModifications($product,$shop_id)
    {
        //订单主表
        $insert = [
            'product_id' => $product['id'] ?? "",
            'title' => $product['title'] ?? "",
            'body_html' => "",
            // 'body_html' => $ApiOrderLogic->removeNonAscii($product['body_html']),
            'vendor' => $product['vendor'] ?? "",
            'product_type' => $product['product_type'] ?? "",
            'tags' => $product['tags'] ?? "",
            'status' => $product['status'] ?? "",
            'created_at' => $product['created_at'] ?? "",
            'updated_at' => $product['updated_at'] ?? "",
            'published_at' => $product['published_at'] ?? "",
        ];

        $sku = '';
        //variants
        if($product['variants'] && is_array($product['variants'])){
            $sku = $this->addvariants($product['id'],$product['variants']);
        }
        //images
        if($product['images'] && is_array($product['images'])){
            $this->addimages($product['id'],$product['images']);
        }
        $insert['sku'] = $sku;
        Db::name('product_api')->where('product_id',$product['id'])->update($insert);
        return true;
    }
    /**
    * 添加variants
    * @param array params
    */
    public function addvariants($product_id,$variants)
    {
        $sku = '';
        $insert = [];
        foreach ($variants as  $variant) {
            //添加variants
            $insert[] = [
                'product_id' => $product_id,
                'sku_id' => $variant['id'] ?? "",
                'title' => $this->removeNonAscii($variant['title']) ?? "",
                'seller_sku' => $variant['sku'] ?? "",
                'price' => $variant['price'] ?? "",
                'option1' => $this->removeNonAscii($variant['option1']) ?? "",
                'option2' => $this->removeNonAscii($variant['option2']) ?? "",
                'option3' => $this->removeNonAscii($variant['option3']) ?? "",
                'image_id' => $variant['image_id'] ?? "",
                'inventory_quantity' => $variant['inventory_quantity'] ?? "",
                'created_at' => $variant['created_at'] ?? "",
                'updated_at' => $variant['updated_at'] ?? "",
            ];
            if(!empty($variant['sku'])){
                $sku = $variant['sku'];
            }
        }
        Db::name('product_sku_api')->where('product_id',$product_id)->delete();
        Db::name('product_sku_api')->insertAll($insert);
        return $sku;
    }

    /**
    * 添加variants
    * @param array params
    */
    public function addimages($product_id,$images)
    {
        $insert = [];
        foreach ($images as  $image) {
            //添加variants
            $insert[] = [
                'product_id' => $product_id,
                'image_id' => $image['id'] ?? "",
                'width' => $image['width'] ?? "",
                'height' => $image['height'] ?? "",
                'src' => $image['src'] ?? "",
                'created_at' => $image['created_at'] ?? "",
                'updated_at' => $image['updated_at'] ?? "",
            ];
        }
        Db::name('product_images_api')->where('product_id',$product_id)->delete();
        Db::name('product_images_api')->insertAll($insert);
        return true;
    }

    

    /**
    * @desc    新增商品
    * @date    2024/11/22
    * @author  zhangheng
    */
    public function products_create($params = [])
    {
        $arr['shop_id']    = $params['shop_id'] ?? 0;
        $arr['product_id'] = $params['id'] ?? 0;
        $arr['json']       = json_encode($params,true);
        $arr['timestamp']  = time();
        $arr['type']       = 1;
        //数据同步到产品表;




        return json(DefaultResponse(200, true, '操作成功', ''));
    }
    /**
    * @desc    修改商品
    * @date    2024/11/22
    * @author  zhangheng
    */
    public function products_updated($params = [])
    {
        $ApiOrderLogic = new ApiOrderLogic();

        $arr['shop_id'] = $params['shop_id'] ?? 0;
        $arr['product_id'] = $params['id'] ?? 0;
        $arr['json'] = json_encode($params,true);
        $arr['timestamp'] = time();
        $arr['type'] = 2;
        table('product_webhooks')->insert($arr);

        Db::startTrans();
        try {
            //新增修改订单
            if(!empty($arr['product_id'])){
                $row = Db::name('product_api')->where('product_id',$arr['product_id'])->find();
                if(empty($row)){
                    $this->SynchronizeModifications($params,$params['shop_id']);
                }else{
                    //更新时间更大就更新
                    $updated_at = $ApiOrderLogic->dateTimeStr($params['updated_at']);
                    $old_updated_at = $ApiOrderLogic->dateTimeStr($row['updated_at']);
                    if($updated_at > $old_updated_at){
                        $this->SynchronizzeModifications($params,$params['shop_id']);
                    }
                }
            }
            Db::commit();
        } catch (ValidateException $e) {
        } catch (\Exception $e) {
            Db::rollback();
        }

        return json(DefaultResponse(200, true, '操作成功', ''));
        
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 产品系列
     * https://shopify.fan-zhou.com/api/ApiProduct/ApiProductCollectionList?shop_id=17
     * @author zhangheng
     */
    public function ApiProductCollectionList($params = [])
    {
        $shop_id        = $params['shop_id'] ?? 0;
        
        if(empty($shop_id)){
            //轮询店铺
            $shop_id = $this->PollingStoresCollection();
            if (empty($shop_id)) {
                return json(DefaultResponse(201, false, '暂无店铺!', null));
            }
        }
        
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
        $version        = Config('Logisticskey.shopify.api_versoin');
        $operation      = Config('Logisticskey.shopify.custom_collections');
        $url            = $shop_info['myshopify_domain'].$version . $operation;
        
        $limit = 250;
        $url = $url . '?limit=' . $limit;

        $return = HttpUtil::getUrl($url, $shop_info);

        if (!empty($return['errors'])) {
            return json(DefaultResponse(201, false, json_encode($return['errors']), null));
        }
        if(!empty($return)){
            $this->ProcessProductCollection($return,$shop_info);
            return json(DefaultResponse(200, true, '操作成功', ''));
        }else{
            return json(DefaultResponse(200, true, '暂无数据', ''));
        }
    }

    /**
    * @desc    产品系列新增修改
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function ProcessProductCollection($return,$shop_info)
    {
        $shop_id = $shop_info['id'];
        $shop_name = $shop_info['name'];
        $custom_collections = $return['custom_collections'];
        if (is_array($custom_collections) && !empty($custom_collections)) {
            date_default_timezone_set('Asia/Shanghai');
            $insert = [];
            foreach ($custom_collections as $collection) {
                $insert[] = [
                    'shop_id' => $shop_id,
                    'shop_name' => $shop_name,
                    'collection' => $this->removeNonAscii($collection['title']) ?? "",
                    'create_time' => $collection['published_at'],
                    'update_time' => $collection['updated_at'],
                ];
            }
            if(!empty($insert)){
                Db::name('shops_collection')->where('shop_id',$shop_id)->delete();
                Db::name('shops_collection')->insertAll($insert);
            }
        }
        return true;
    }
    

    public function PollingStoresCollection()
    {
        $where2[] = ['type', '=', "shopify"];
        $shop_id = 0;
        $shops = Cache::store('redis')->get('shops_shopify_collection');
        if (empty($shops)) {  
            $shopRecords = Db::name('shops')
                ->where($where2)
                ->where('status',1)
                ->field("id")->select()->toarray();
            if(!empty($shopRecords)){
                $shops = array_column($shopRecords, 'id');
                Cache::store('redis')->set('shops_shopify_collection', $shops, 3600 * 24); // 缓存24小时  
            }
        } 
        if (!empty($shops)) {  
            $shop_id = array_shift($shops); 
            if (!empty($shops)) {  
                Cache::store('redis')->set('shops_shopify_collection', $shops, 3600 * 24);
            }else{
                Cache::store('redis')->delete('shops_shopify_collection');
            }
        }
        return $shop_id;
    }
    
    public function removeNonAscii($string) {  
        $output = '';  
        for ($i = 0; $i < mb_strlen($string, 'UTF-8'); $i++) {  
            $char = mb_substr($string, $i, 1, 'UTF-8');  
            if (ord($char[0]) < 128) {  
                $output .= $char;  
            }  
        }  
        return $output;  
    }


    /**
     * @desc    获取shopify的token
     * @author  xx
     * @date    2024-12-27
     */
    public function get_shopify_token($params=[]){
           $shop_id = $params['shop_id']??'';
           $info    = Db::name('shops')->where('id',$shop_id)->find();
           $apikey        = $info['app_key']??'';
           $secretapikey  = $info['app_secret']??'';
           return base64_encode("$apikey:$secretapikey");
    }


    

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 产品转移
     * @author zhangheng
     */
    public function ApiProductTransfer($params = [])
    {
        $shop_id        = $params['shop_id'] ?? 0;
        $product_id        = $params['product_id'] ?? 0;
        $new_shop_id        = $params['new_shop_id'] ?? 0;
        $data        = $params ?? [];
        if(empty($shop_id)){
            return json(DefaultResponse(201, false, '暂无店铺!', null));
        }
        if(empty($product_id)){
            return json(DefaultResponse(201, false, '暂无产品!', null));
        }
        if(empty($new_shop_id)){
            return json(DefaultResponse(201, false, '暂无转移店铺!', null));
        }
        if(empty($data)){
            return json(DefaultResponse(201, false, '暂无数据!', null));
        }
        
        //最新信息
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
        $version        = Config('Logisticskey.shopify.api_versoin');
        $operation      = Config('Logisticskey.shopify.operation');
        $url            = $shop_info['myshopify_domain'].$version . $operation."?ids=".$product_id;

        $return = HttpUtil::getUrl($url, $shop_info);

        if (!empty($return['errors'])) {
            return json(DefaultResponse(201, false, json_encode($return['errors']), null));
        }
        //添加产品需要的参数
        $data = [];
        $product = $return['products'][0] ?? [];
        if(empty($product)){
            return json(DefaultResponse(201, false, '产品为空!', null));
        }
        unset($product['id']);
        unset($product['image']['id']);
        unset($product['image']['product_id']);
        if(!empty($product['images'])){
            foreach ($product['images'] as &$v){
                unset($v['product_id']);
                unset($v['id']);
            }
        }
        if(!empty($product['variants'])){
            foreach ($product['variants'] as &$v){
                unset($v['product_id']);
                unset($v['id']);
                unset($v['image_id']);
            }
        }
        if(!empty($product['options'])){
            foreach ($product['options'] as &$v){
                unset($v['product_id']);
                unset($v['id']);
            }
        }
        $data['product'] = $product;
        // halt($data);
        
        // halt($data);
        $shop_info      = Db::name('shops')->where('id',$new_shop_id)->find();
        $operation      = Config('Logisticskey.shopify.operation');
        $url            = $shop_info['myshopify_domain'].$version . $operation;
        $return = HttpUtil::postUrl($url,$data,$shop_info);
        $return =  json_decode($return, true);
        // halt($return);
        if (!empty($return['errors'])) {
            return json(DefaultResponse(201, false, json_encode($return['errors']), null));
        }
        if (isset($return['product']['id']) && !empty($return['product']['id'])) {
            $product_id = $return['product']['id'];
            return json(DefaultResponse(200, true, '产品转移成功',$product_id));
        }
        return json(DefaultResponse(201, true, '产品转移失败',$return));
    }

    

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 产品系列
     * https://shopify.fan-zhou.com/api/ApiProduct/ApiProductCollectionList?shop_id=17
     * @author zhangheng
     */
    public function ApiProductCollectionTransfer($params = [])
    {
        $shop_id        = $params['shop_id'] ?? 0;
        $new_shop_id        = $params['new_shop_id'] ?? 0;
        
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
        $version        = Config('Logisticskey.shopify.api_versoin');
        $operation      = Config('Logisticskey.shopify.custom_collections');
        $url            = $shop_info['myshopify_domain'].$version . $operation;
        
        $limit = 250;
        $url = $url . '?limit=' . $limit;

        $return = HttpUtil::getUrl($url, $shop_info);
        // halt($return);
        if (!empty($return['errors'])) {
            return json(DefaultResponse(201, false, json_encode($return['errors']), null));
        }

        $shop_info      = Db::name('shops')->where('id',$new_shop_id)->find();
        $operation      = Config('Logisticskey.shopify.operation');
        $url            = $shop_info['myshopify_domain'].$version . '/custom_collections.json';
        $custom_collections = $return['custom_collections'] ?? [];
        if(!empty($custom_collections)){
            foreach ($custom_collections as $k=>$v) {
                $data = [];
                unset($v['id']);
                $data['custom_collection'] = $v;
                // halt($data);
                $return = HttpUtil::postUrl($url,$data,$shop_info);
                $return =  json_decode($return, true);
            }

            return json(DefaultResponse(200, true, '操作成功', $return));
        }else{
            return json(DefaultResponse(200, true, '暂无数据', $return));
        }
    }


}
